package com.wxtf.platform.plugins.filter;

import java.io.IOException;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wxtf.platform.plugins.user.UserBean;

/**
 * <li>Title: UserAuthorFilter.java</li>
 * <li>Project: baseplatform</li>
 * <li>Package: com.wxtf.platform.plugins.filter</li>
 * <li>Description: 用户登录验证</li>
 * <li>Copyright: Copyright (c) 2012</li>
 * <li>Company: wxthtf Technologies </li>
 * <li>Created on Jul 25, 2012 4:43:37 PM</li>
 *
 * @author chun_chang
 * @version 1.0.0.0
 *
 */
public class UserAuthorFilter extends HttpServlet implements Filter{
	private static final long serialVersionUID = 1081886117436613862L;
	private static Log log = LogFactory.getLog(UserAuthorFilter.class);

	private FilterConfig filterConfig;
	private String[] freePages;
	private String toPage = null;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		int i = 0;
		String pages = null;
		StringTokenizer strTokenizer = null;

		this.filterConfig = filterConfig;
		// 以下从配置文件获取配置信息
		this.toPage = filterConfig.getInitParameter("toPage");
		pages = filterConfig.getInitParameter("AllowURL");
		if(toPage == null || pages == null || toPage.trim().length() == 0 || pages.trim().length() == 0) {
			log.error("web.xml中filterServlet没有配置初始化参数\"toPage\"或\"AllowURL\".");
			throw new ServletException("web.xml中filterServlet没有配置初始化参数\"toPage\"或\"AllowURL\".");
		}

		strTokenizer = new StringTokenizer(pages, ";");
		this.freePages = new String[strTokenizer.countTokens()];
		while(strTokenizer.hasMoreTokens()) {
			freePages[i++] = strTokenizer.nextToken();
		}
		if(!isFreePage(toPage)) {
			log.error("web.xml中filter初始化参数\"toPage\"的值必须是\"AllowURL\"中的某个页面.");
			throw new ServletException("web.xml中filter初始化参数\"toPage\"的值必须是\"AllowURL\"中的某个页面.");
		}
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest request = (HttpServletRequest) req;

		// AUTH_STATUS success代表成功，failure代表失败
		String requestURI = null;
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		requestURI = httpRequest.getRequestURI();
		String contextPath = request.getContextPath() + "/";
		//不是工程路径 不是保护页面  Session无效，跳转错误页面
		if(!contextPath.equals(requestURI) && !isFreePage(requestURI) && !isValidSession(request)) {
			log.info("非法请求的URI：" + requestURI);
			String toPageURL = httpRequest.getContextPath() + toPage + "?from=server";
			httpResponse.encodeRedirectURL(toPageURL);
			httpResponse.sendRedirect(toPageURL);
		}

		// 如果响应未提交,交给过滤器链
		if(!httpResponse.isCommitted()) {
			try {
				chain.doFilter(request, response);
			} catch(ServletException sx) {
				filterConfig.getServletContext().log(sx.getMessage());
				log.error(sx, sx);
			} catch(IOException iox) {
				log.error(iox, iox);
				filterConfig.getServletContext().log(iox.getMessage());
			}
		}
	}

	@Override
	public void destroy() {

	}

	/**
	 * 判断一个请求URI是否是不过滤的页面
	 * @param requestURI String 请求URI
	 * @return boolean 返回true为不过滤页面
	 */
	private boolean isFreePage(String requestURI) {
		for(int i = 0; i < freePages.length; i++) {
			if(requestURI.endsWith(freePages[i])) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 判断请求是否为有效Session
	 * @param request ServletRequest 请求对象
	 * @return boolean 返回true为有效Session
	 */
	private boolean isValidSession(ServletRequest request) {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		UserBean user = (UserBean) httpRequest.getSession().getAttribute("userBean");
		if(null == user || StringUtils.isBlank(user.getUserId())
				|| StringUtils.isBlank(user.getCurOrgId())) {
			return false;
		}
		return true;
	}

	public FilterConfig getFilterConfig() {
		return this.filterConfig;
	}

	public void setFilterConfig(FilterConfig filterConfig) {
		this.filterConfig = filterConfig;
	}

}
